<template>
  <div class="condition-form action-app-form" v-if="app&&app.data">
    <div class="action-app-form-item">
      <div class="title">{{ $t('common.base.rulerName') }}</div>
      <el-input v-model="app.data.name" maxlength="20" show-word-limit></el-input>
    </div>
    <div class="action-app-form-item">
      <div class="title" v-if="!isShowCode">配置方式</div>
      <el-radio-group v-model="convertType" style="margin: 10px 0;" v-else>
        <el-radio-button :label="'fieldMapping'">配置方式</el-radio-button>
        <el-radio-button :label="'convertCode'">代码方式</el-radio-button>
      </el-radio-group>
      <div class="content" v-loading="loading" v-if="convertType == 'fieldMapping'">
        <template v-if="init">
          <div class="condition-group-item" v-for="(group,index) in conditionList" :key="index">
            <span class="delete-btn" @click="delConditionGroup(index)" v-if="index>0"><i class="iconfont icon-delete"></i> {{ $t('common.paas.view.designer.workFlow.deleteConditionGroup')}}</span>
            <p v-if="index>0" style="margin-bottom:6px;">{{ $t('common.paas.view.designer.workFlow.or')}}</p>
            <ConnectorModuleConnectorDialogDetailActionQuery
              :toFieldList="toFieldList"
              :fromFieldList="toFieldList"
              :toBizTypeName="toBizTypeName"
              :value="group"
              :fromBizTypeName="fromBizTypeName"
              @input="val=>{onConnectorSelectRuleFormInputHandler(val,index)}"
              justFixedValue
              :showHeader="false"
              :showSelectTip="false"
              :nodeConfig="nodeConfig"
              :isMultipleChoose="true"
            />
          </div>
        </template>
        <el-button type="primary" plain @click="addConditionGroup">+ {{ $t('common.paas.view.designer.workFlow.orCondition')}}</el-button>
      </div>
      <div class="content content-code" v-else>
        <el-button type="text" @click="openCodeHelp">编码规范及使用帮助</el-button>
        <action-codemirror :value.sync="convertCode"></action-codemirror>
      </div>
    </div>
  </div>
</template>
<script>
import * as triggerApi from '@src/modules/connector/api/trigger';
import { ConnectorModuleConnectorDialogDetailActionQuery } from '@src/modules/connector/components';
import _ from 'lodash'
import { addSupportProperty, getToStartNodeFromApiId } from '@src/modules/connector/view/setting/components/workflow/utils/index.js';
import actionCodemirror from '@src/modules/connector/view/setting/components/workflow/components/drawers/actionCodemirror.vue'
import { getAllGrayInfo } from '@src/util/grayInfo'
import { condition } from '@src/modules/connector/util/sampleCode.ts'

export default {
  name: 'condition-drawer',
  provide: {
    isTrigger: true,
  },
  props: {
    nodeConfig: {
      type: Object,
      default: () => ({}),
    },
    parent: {
      type: Object,
      default: () => ({}),
    },
  },
  created() {
    getAllGrayInfo().then(res => {
      this.isShowCode = res?.TRIGGER_CODE;
    })
    this.updateConvertType();
  },
  watch: {
    nodeConfig: {
      handler(newVal) {
        this.app = newVal;
        this.convertType = this.nodeConfig.data.convertType || 'fieldMapping'
        this.conditionList = this.nodeConfig.data.conditionList || [[]]
        this.convertCode = this.nodeConfig.data.convertCode || condition
        this.updateConvertCode();
      },
      deep: true,
      immediate: true,
    },
    parentApp: {
      handler(newVal) {
        this.getFieldList();
        this.fromBizTypeName = newVal.name || ''
      },
      deep: true,
      immediate: true,
    },
    conditionList:{
      handler(newVal) {
        this.$nextTick(() => {
          this.userNameStyleOverlapPolyfill()
        })
      },
      deep: true,
      immediate: true,
    },
    convertType: {
      handler(newVal) {
        this.updateConvertType()
      },
    },
    convertCode: {
      handler(newVal) {
        this.updateConvertCode()
      },
    }
  },
  computed: {
    parentApp() {
      return this.parent.isTrigger
        ? this.parent.getParent().data
        : this.parent.data;
    },
    toBizTypeName() {
      return '';
    },
    parentAppBizTypeIds () {
      return getToStartNodeFromApiId(this.nodeConfig, [])
    }
  },
  data() {
    return {
      app: null,
      conditionList: [[]],
      toFieldList: [],
      fromFieldList: [],
      fromBizTypeName: '',
      loading: true,
      init: false,
      convertType: 'fieldMapping',
      convertCode: condition,
      isShowCode: false,
    };
  },
  methods: {
    // fetchFromF
    getFieldList() {
      // let { bizTypeId } = this.parentApp;
      this.loading = true
      triggerApi.getConditionConfig(this.parentAppBizTypeIds).then(res => {
        this.init = true
        if (res.status == 0) {
          this.toFieldList = addSupportProperty(res.data || [], 'supportSelect')
        }
        this.$nextTick(() => {
          this.userNameStyleOverlapPolyfill()
        })
        
      }).finally(()=> this.loading = false);
    },
    onConnectorSelectRuleFormInputHandler(val,index) {
      this.conditionList[index] = val
      this.updateConditionList()
    },
    /**
     * @description 用户名样式重叠补丁
     */
    userNameStyleOverlapPolyfill() {
      
      const userInputList = this.$el.querySelectorAll('.user-search input') || []
      
      userInputList.forEach(userInputElement => {
        if (userInputElement.value) {
          userInputElement.value = ''
          userInputElement.placeholder = ''
        }
      })
      
    },
    addConditionGroup(){
      this.conditionList.push([])
      this.updateConditionList()
    },
    delConditionGroup(index){
      this.conditionList.splice(index, 1)
      this.updateConditionList()
    },
    updateConditionList(){
      this.nodeConfig.data.conditionList = _.cloneDeep(this.conditionList);
      this.$emit('update:nodeConfig', this.nodeConfig);
      this.$nextTick(() => {
        this.userNameStyleOverlapPolyfill()
      })
    },
    updateConvertType() {
      this.nodeConfig.data.convertType = this.convertType;
      this.$emit('update:nodeConfig', this.nodeConfig);
    },
    updateConvertCode() {
      this.nodeConfig.data.convertCode = this.convertCode;
      this.$emit('update:nodeConfig', this.nodeConfig);
    },
    // 打开编码规范及使用帮助
    openCodeHelp(){
      window.open('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/gre7yumc5sz4ewod/dklg7gkm64cya8l4/ox8c8k8i3hp1g6do.html');
    }
  },
  components: {
    ConnectorModuleConnectorDialogDetailActionQuery,
    actionCodemirror,
  },
};
</script>
<style lang="scss" scoped>
.condition-form{
  ::v-deep  .el-button--primary.is-plain{
    color: $color-primary-light-6 !important;
    background-color: $color-primary-light-1 !important;
  }
  .condition-group-item{
    position: relative;
    .delete-btn{
      display: flex;
      align-items: center;
      line-height: 24px;
      position: absolute;
      left: 140px;
      top: 40px;
      color:#8C8C8C;
      cursor: pointer;
      &:hover{
        color: #f56c6c;
      }
    }
  }
  .action-app-form-item:nth-last-of-type(1) {
    div:nth-last-of-type(1) {
      margin-top: 0;
    }
  }
}
.content-code {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  .el-button {
    margin-bottom: 10px;
  }
  .action-app-codemirror {
    width: 100%;
  }
}
</style>
